#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>

int main(int argc, char const *argv[])
{
    struct sockaddr_in client_addr;
    struct sockaddr_in server_addr;

    server_addr.sin_addr.s_addr = inet_addr("192.168.13.66");
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8888);

    int server_sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (server_sock < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    socklen_t client_addr_len = sizeof(client_addr);
    socklen_t server_addr_len = sizeof(server_addr);

    if (bind(server_sock, (struct sockaddr *)&server_addr, server_addr_len) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    char *recv_buf = malloc(1024 * sizeof(char));
    char *send_buf = malloc(1024 * sizeof(char));

    while (1) {
        memset(recv_buf, 0, 1024);
        memset(send_buf, 0, 1024);

        recvfrom(server_sock, recv_buf, 1024, 0, (struct sockaddr *)&client_addr, &client_addr_len);

        // 如果接收到的消息是 "exit"，则退出循环
        if (strcmp(recv_buf, "exit\n") == 0) {
            sprintf(send_buf, "exit");
            sendto(server_sock, send_buf, strlen(send_buf), 0, (struct sockaddr *)&client_addr, client_addr_len);
            break;
        }

        sprintf(send_buf, "success");
        printf("Received from %s:%d: %s\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), recv_buf);

        sendto(server_sock, send_buf, strlen(send_buf), 0, (struct sockaddr *)&client_addr, client_addr_len);
    }

    printf("Server exit\n");

    close(server_sock);
    free(recv_buf);
    free(send_buf);

    return 0;
}
